package com.szcinda.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.szcinda.controller.configuration.UserLoginToken;
import com.szcinda.repository.Coach;
import com.szcinda.service.dto.coach.CoachExcelListener;
import com.szcinda.service.dto.coach.CoachImportDto;
import com.szcinda.service.dto.coach.CoachService;
import com.szcinda.service.dto.coach.CreateCoachDto;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("coach")
public class CoachController {

    private final CoachService coachService;

    public CoachController(CoachService coachService) {
        this.coachService = coachService;
    }


    @UserLoginToken
    @PostMapping("create")
    @OperationLogAnnotation(operDesc = "新增口岸信息", operModel = "口岸信息维护")
    public Result<String> create(@RequestBody CreateCoachDto createDto) {
        coachService.create(createDto);
        return Result.success();
    }

    @GetMapping("delete/{id}/{userId}")
    @OperationLogAnnotation(operDesc = "删除口岸信息", operModel = "口岸信息维护")
    public Result<String> del(@PathVariable String id, @PathVariable String userId) {
        coachService.delete(id, userId);
        return Result.success();
    }

    @UserLoginToken
    @GetMapping("all")
    public Result<List<Coach>> query() {
        return Result.success(coachService.findAll());
    }


    @PostMapping("/import/{opId}")
    @OperationLogAnnotation(operDesc = "导入口岸信息", operModel = "口岸信息维护")
    public Result<String> orderImport(@RequestParam("file") MultipartFile file, @PathVariable String opId) throws Exception {
        InputStream inputStream = file.getInputStream();
        try {
            CoachExcelListener listener = new CoachExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, CoachImportDto.class), listener);
            coachService.batchCreate(listener.getImportDatas(), opId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
